<template>
  <div style="margin-left: 50px">
    <div style="display: flex">
      <span style="font-size: 20px">{{ $t('menu.myCollection') }}</span>
      <div style="margin-left: 5px;margin-right: 5px">
        <el-input placeholder="请输入关键字，如有多条件用，隔开" v-model="state.searchInfo" style="width: 200px"></el-input>
        <el-button style="margin-left: 5px" type="success" @click="searchFileInfo">
          <el-icon>
            <Search/>
          </el-icon>
        </el-button>
      </div>
    </div>
    <el-table
        style="width: 1200px"
        :data="state.fileList"
        :default-sort="[{ prop: 'fileName', order: 'fileName' },{ prop: 'registerDate', order: 'descending' }]"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30"/>
      <el-table-column prop="fileName" sortable label="文件名"/>
      <el-table-column prop="filePackage" label="文件夹"/>
      <el-table-column prop="fileCapacity" label="大小"/>
      <el-table-column prop="creationTime" label="创建时间"/>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <!--        link控制按键-->
          <el-dropdown>
            <template #dropdown>
              下载
            </template>
              <el-button type="primary" size="small" style="margin-right: 10px" @click="downloadFile(scope.row)">
                <el-icon>
                  <Download/>
                </el-icon>
                <!--              下载-->
              </el-button>
          </el-dropdown>
          <el-dropdown>
            <template #dropdown>
              分享
            </template>
            <el-button type="primary" size="small"  @click="openShareFilesDialog(scope.row)" style="margin-right: 10px">
              <el-icon>
                <Position/>
              </el-icon>
              <!--            分享-->
            </el-button>
          </el-dropdown>
<!--          <el-dropdown>-->
<!--            <template #dropdown>-->
<!--              收藏-->
<!--            </template>-->
<!--          <el-button type="primary" size="small" @click="collectionFileInfo(scope.row)">-->
<!--            <el-icon>-->
<!--              <Star/>-->
<!--            </el-icon>-->
            <!--            收藏-->
<!--          </el-button>-->
<!--          </el-dropdown>-->
          <el-dropdown>
            <template #dropdown>
              移除
            </template>
          <el-button type="primary" size="small" @click="removeCollectionFileInfo(scope.row)" style="margin-right: 10px">
            <el-icon>
              <Delete/>
            </el-icon>
            <!--            移除-->
          </el-button>
          </el-dropdown>
            <el-dropdown>
                <template #dropdown>
                    预览
                </template>
                <el-toolTip content="预览" placement="bottom" effect="light">
                    <el-button v-if="previewList.includes(scope.row.fileName.split('.')[1])" type="primary" size="small" @click="openPreviewDialog(scope.row)"
                               style="margin-right: 10px">
                        <el-icon><Sunny /></el-icon>
                        <!--            预览-->
                    </el-button>
                </el-toolTip>
            </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total=total
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
    </div>
    <el-dialog
        v-model="shareFilesDialog"
        title="分享文件"
        width="50%"
    >

        <span>邮箱</span>
        <el-input v-model="state.sendEmail" style="width:200px;margin-left: 10px"></el-input>
        <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="shareFilesInfo">确认</el-button>
      </span>
        </template>
    </el-dialog>
      <el-dialog
          v-model="previewDialog"
          title="预览"
          width="30%"
      >
          <div>
              <el-image style="width: 475px; height: 500px" :src="state.openImgUrl"/>
          </div>
          <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="shareFilesDialog = false">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref, watch} from "vue";
import {Position, Download, Star, Delete, Search,Sunny} from "@element-plus/icons-vue"
import request from "../request"
import ElNotification, {ElMessage} from "element-plus";
import COS from "cos-js-sdk-v5";

const state = reactive({
    fileList: [],
    searchInfo: "",
    fileInfo: {},
    sendEmail: "",
    openImgUrl: '',
})

// 默认初始位置
const currentPage = ref(1)
// 默认每页个数
const pageSize = ref(10)
const searchInfo = ref('')
const total = ref(10)
const shareFilesDialog=ref(false)
const previewDialog = ref(false)
const previewList = ['png','jpg','PNG','JPG']
onMounted(() => {
  searchFileInfo()
})

const handleSizeChange = (val) => {
  pageSize.value = val
  searchFileInfo()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  searchFileInfo()
}
const searchFileInfo = () => {
  request.get('file/queryCollectionInfo', {
    params: {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      searchInfo: state.searchInfo,
    }
  }).then(res => {
      if (res.success) {
          state.fileList = res.data.data
          for (let i of state.fileList) {
              i.fileCapacity = sizeTostr(parseInt(i.fileCapacity))
          }
          total.value = res.data.total
      } else {
      ElNotification.error(res.msg)
    }
  })
}

const openPreviewDialog = (fileInfo) => {
    state.openImgUrl = fileInfo.filePath
    previewDialog.value = true
}

const handleSelectionChange = () => {

}
const sizeTostr = (size) => {

    console.info(size)
    let data = "";
    if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
    } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
    } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
    } else { //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }
    let sizestr = data + "";
    let len = sizestr.indexOf("\\.");
    let dec = sizestr.substr(len + 1, 2);
    if (dec == "00") {
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }
    return sizestr;
}

// 分享文件对话框
const openShareFilesDialog = (file) => {
  state.shareFileUrl = file.filePath;
  shareFilesDialog.value = true;
}

//文件移除
const removeCollectionFileInfo = (file) => {
  request.post('file/removeCollectionInfo', file).then(res => {
    if (res.success) {
      ElMessage.success(res.msg)
      searchFileInfo()
    }
  })
}

// 文件收藏
const collectionFileInfo = (file) => {
  request.post('file/collectionFileInfo', file).then(res => {
    if (res.success) {
      ElMessage.success(res.msg)
      searchFileInfo()
    }
  })
}
//文件下载
const downloadFile = (fileInfo) => {
    request.get('file/getTencentCosInfo', {timeout: 10000}).then(res => {
        if (res.success) {
            const tencentCos = res.data
            const cos = new COS({
                SecretId: tencentCos.secretId,
                SecretKey: tencentCos.secretKey,
            })
            const pathArr = fileInfo.filePath.split('/')
            const filepath = 'file/' + pathArr[pathArr.length - 1]
            cos.getObjectUrl({
                Bucket: tencentCos.bucket,
                Region: tencentCos.region,     /* 存储桶所在地域，必须字段 */
                Key: filepath,
                Sign: true
            }, function (err, data) {
                if (err) {
                    return console.log(err)
                }
                const downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment'; // 补充强制下载的参数
                window.open(downloadUrl); // 这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载
            })
        }
    })
}
</script>
